package com.example.websocket.service;

import com.example.websocket.vo.WsMsgVo;
import jakarta.websocket.*;
import jakarta.websocket.server.ServerEndpoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author wwl
 * @version 1.0
 * @date 2024/8/26 15:06
 * @description:
 */
@Slf4j
@Component
@ServerEndpoint("/ws/demo3")
public class Ws3Handler {
    @OnOpen
    public void onOpen(Session session) {
        Ws3Pool.add(session);
    }

    @OnClose
    public void OnClose(Session session) {
        Ws3Pool.remove(session);
    }

    @OnMessage
    public void onMessage(Session session, String message) throws IOException {
        if ("ping".equals(message)) {
            // 心跳消息
            session.getBasicRemote().sendText("pong");
            return;
        }
        log.info("receive Msg :" + message);
//        session.getBasicRemote().sendText(message);
        Ws3Pool.broadcast(new WsMsgVo(message, 0L));
    }

    /**
     * 错误时调用
     */
    @OnError
    public void onError(Session session, Throwable throwable) {
        throwable.printStackTrace();
    }
}
